home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / sbin / update-apt-xapian-index < prev    next >
Text File  |  2008-08-20  |  21KB  |  625 lines

  1. #!/usr/bin/python
  2.  
  3. #
  4. # update-apt-xapian-index - Maintain a system-wide Xapian index of Debian
  5. #                           package information
  6. #
  7. # Copyright (C) 2007  Enrico Zini <enrico@debian.org>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  22. #
  23.  
  24. import os
  25.  
  26. # Setup configuration
  27. PLUGINDIR = os.environ.get("AXI_PLUGIN_DIR", "/usr/share/apt-xapian-index/plugins")
  28. XAPIANDBPATH = os.environ.get("AXI_DB_PATH", "/var/lib/apt-xapian-index")
  29. XAPIANDBSTAMP = XAPIANDBPATH + "/update-timestamp"
  30. XAPIANDBLOCK = XAPIANDBPATH + "/update-lock"
  31. XAPIANDBUPDATESOCK = XAPIANDBPATH + "/update-socket"
  32. XAPIANDBVALUES = XAPIANDBPATH + "/values"
  33. XAPIANDBDOC = XAPIANDBPATH + "/README"
  34.  
  35. class Progress:
  36.     def __init__(self):
  37.         self.task = None
  38.         self.halfway = False
  39.         self.is_verbose = False
  40.     def begin(self, task):
  41.         self.task = task
  42.         print "%s..." % self.task,
  43.         sys.stdout.flush()
  44.         self.halfway = True
  45.     def progress(self, percent):
  46.         print "\r%s... %d%%" % (self.task, percent),
  47.         sys.stdout.flush()
  48.         self.halfway = True
  49.     def end(self):
  50.         print "\r%s: done.  " % self.task
  51.         self.halfway = False
  52.     def verbose(self, *args):
  53.         if not self.is_verbose: return
  54.         if self.halfway:
  55.             print
  56.         print " ".join(args)
  57.         self.halfway = False
  58.     def notice(self, *args):
  59.         if self.halfway:
  60.             print
  61.         print >>sys.stderr, " ".join(args)
  62.         self.halfway = False
  63.     def warning(self, *args):
  64.         if self.halfway:
  65.             print
  66.         print >>sys.stderr, " ".join(args)
  67.         self.halfway = False
  68.     def error(self, *args):
  69.         if self.halfway:
  70.             print
  71.         print >>sys.stderr, " ".join(args)
  72.         self.halfway = False
  73.  
  74. class BatchProgress:
  75.     def __init__(self):
  76.         self.task = None
  77.     def begin(self, task):
  78.         self.task = task
  79.         print "begin: %s\n" % self.task,
  80.         sys.stdout.flush()
  81.     def progress(self, percent):
  82.         print "progress: %d/100\n" % percent,
  83.         sys.stdout.flush()
  84.     def end(self):
  85.         print "done: %s\n" % self.task
  86.         sys.stdout.flush()
  87.     def verbose(self, *args):
  88.         print "verbose: %s" % (" ".join(args))
  89.         sys.stdout.flush()
  90.     def notice(self, *args):
  91.         print "notice: %s" % (" ".join(args))
  92.         sys.stdout.flush()
  93.     def warning(self, *args):
  94.         print "warning: %s" % (" ".join(args))
  95.         sys.stdout.flush()
  96.     def error(self, *args):
  97.         print "error: %s" % (" ".join(args))
  98.         sys.stdout.flush()
  99.  
  100. class SilentProgress:
  101.     def begin(self, task):
  102.         pass
  103.     def progress(self, percent):
  104.         pass
  105.     def end(self):
  106.         pass
  107.     def verbose(self, *args):
  108.         pass
  109.     def notice(self, *args):
  110.         pass
  111.     def warning(self, *args):
  112.         print >>sys.stderr, " ".join(args)
  113.     def error(self, *args):
  114.         print >>sys.stderr, " ".join(args)
  115.  
  116. class ClientProgress:
  117.     def __init__(self, progress):
  118.         self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  119.         self.sock.connect(XAPIANDBUPDATESOCK)
  120.         self.progress = progress
  121.  
  122.     def loop(self):
  123.         hasBegun = False
  124.         while True:
  125.             msg = self.sock.recv(4096)
  126.             try:
  127.                 args = pickle.loads(msg)
  128.             except EOFError:
  129.                 progress.error("The other update has stopped")
  130.                 return
  131.             action = args[0]
  132.             args = args[1:]
  133.             if action == "begin":
  134.                 progress.begin(*args)
  135.                 hasBegun = True
  136.             elif action == "progress":
  137.                 if not hasBegun:
  138.                     progress.begin(args[0])
  139.                     hasBegun = True
  140.                 progress.progress(*args[1:])
  141.             elif action == "end":
  142.                 if not hasBegun:
  143.                     progress.begin(args[0])
  144.                     hasBegun = True
  145.                 progress.end(*args[1:])
  146.             elif action == "verbose":
  147.                 progress.verbose(*args)
  148.             elif action == "notice":
  149.                 progress.notice(*args)
  150.             elif action == "error":
  151.                 progress.error(*args)
  152.             elif action == "alldone":
  153.                 break
  154.             else:
  155.                 progress.error("unknown action '%s' from other update-apt-xapian-index.  Arguments: '%s'" % (action, ", ".join(map(repr, args))))
  156.  
  157.  
  158. class ServerSenderProgress:
  159.     def __init__(self, sock, task = None):
  160.         self.sock = sock
  161.         self.task = task
  162.     def __del__(self):
  163.         self._send(pickle.dumps(("alldone",)))
  164.     def _send(self, text):
  165.         try:
  166.             self.sock.send(text)
  167.         except:
  168.             pass
  169.     def begin(self, task):
  170.         self.task = task
  171.         self._send(pickle.dumps(("begin", self.task)))
  172.     def progress(self, percent):
  173.         self._send(pickle.dumps(("progress", self.task, percent)))
  174.     def end(self):
  175.         self._send(pickle.dumps(("end", self.task)))
  176.     def verbose(self, *args):
  177.         self._send(pickle.dumps(("verbose",) + args))
  178.     def notice(self, *args):
  179.         self._send(pickle.dumps(("notice",) + args))
  180.     def warning(self, *args):
  181.         self._send(pickle.dumps(("warning",) + args))
  182.     def error(self, *args):
  183.         self._send(pickle.dumps(("error",) + args))
  184.  
  185. class ServerProgress:
  186.     def __init__(self, mine):
  187.         self.task = None
  188.         self.proxied = [mine]
  189.         self.sockfile = XAPIANDBUPDATESOCK
  190.         try:
  191.             os.unlink(self.sockfile)
  192.         except OSError:
  193.             pass
  194.         self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  195.         self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  196.         self.sock.bind(XAPIANDBUPDATESOCK)
  197.         self.sock.setblocking(False)
  198.         self.sock.listen(5)
  199.         # Disallowing unwanted people to mess with the file is automatic, as
  200.         # the socket has the ownership of the user we're using, and people
  201.         # can't connect to it unless they can write to it
  202.     def __del__(self):
  203.         self.sock.close()
  204.         os.unlink(self.sockfile)
  205.     def _check(self):
  206.         try:
  207.             sock = self.sock.accept()[0]
  208.             self.proxied.append(ServerSenderProgress(sock, self.task))
  209.         except socket.error, e:
  210.             if e.args[0] != errno.EAGAIN:
  211.                 raise
  212.         pass
  213.     def begin(self, task):
  214.         self._check()
  215.         self.task = task
  216.         for x in self.proxied: x.begin(task)
  217.     def progress(self, percent):
  218.         self._check()
  219.         for x in self.proxied: x.progress(percent)
  220.     def end(self):
  221.         self._check()
  222.         for x in self.proxied: x.end()
  223.     def verbose(self, *args):
  224.         self._check()
  225.         for x in self.proxied: x.verbose(*args)
  226.     def notice(self, *args):
  227.         self._check()
  228.         for x in self.proxied: x.notice(*args)
  229.     def warning(self, *args):
  230.         self._check()
  231.         for x in self.proxied: x.warning(*args)
  232.     def error(self, *args):
  233.         self._check()
  234.         for x in self.proxied: x.error(*args)
  235.  
  236.  
  237. class Addon:
  238.     def __init__(self, file):
  239.         self.name = os.path.basename(file)
  240.         self.name = os.path.splitext(self.name)[0]
  241.         self.filename = os.path.basename(file)
  242.         self.module = imp.load_source(self.name, file)
  243.         self.obj = self.module.init()
  244.         if self.obj:
  245.             self.info = self.obj.info()
  246.  
  247. #
  248. # Function definitions
  249. #
  250.  
  251. def readPlugins(plugindir, progress):
  252.     """
  253.     Read the addons, in sorted order
  254.     """
  255.     addons = []
  256.     for file in sorted(glob.glob(PLUGINDIR+"/*.py")):
  257.         progress.verbose("Reading plugin %s." % file)
  258.         # Skip non-files and hidden files
  259.         if not os.path.isfile(file) or file[0] == '.':
  260.             continue;
  261.         addon = Addon(file)
  262.         if addon.obj != None:
  263.             addons.append(addon)
  264.     return addons
  265.  
  266. def buildIndex(pathname, addons, progress):
  267.     """
  268.     Create a new Xapian index with the content provided by the addons
  269.     """
  270.     progress.begin("Rebuilding Xapian index")
  271.  
  272.     # Create a new Xapian index
  273.     db = xapian.WritableDatabase(pathname, xapian.DB_CREATE_OR_OVERWRITE)
  274.     # It seems to be faster without transactions, at the moment
  275.     #db.begin_transaction(False)
  276.  
  277.     # Iterate all Debian packages
  278.  
  279.     # force apt to not write a pkgcache.bin
  280.     cache = apt.Cache(memonly=True)
  281.     count = len(cache)
  282.     for idx, pkg in enumerate(cache):
  283.         # Print progress
  284.         if idx % 200 == 0: progress.progress(100*idx/count)
  285.  
  286.         document = xapian.Document()
  287.  
  288.         # The document data is the package name
  289.         document.set_data(pkg.name)
  290.  
  291.         # Index the package name with a special prefix, to be able to find this
  292.         # document by exact package name match
  293.         document.add_term("XP"+pkg.name)
  294.  
  295.         # Have all the various plugins index their things
  296.         for addon in addons:
  297.             addon.obj.index(document, pkg)
  298.  
  299.         # Add the document to the index
  300.         db.add_document(document)
  301.     #db.commit_transaction();
  302.     db.flush()
  303.     progress.end()
  304.  
  305. def buildIndexDeb822(pathname, records, addons, progress):
  306.     """
  307.     Create a new Xapian index with the content provided by the addons
  308.     """
  309.     progress.begin("Rebuilding Xapian index")
  310.  
  311.     # Create a new Xapian index
  312.     db = xapian.WritableDatabase(pathname, xapian.DB_CREATE_OR_OVERWRITE)
  313.     # It seems to be faster without transactions, at the moment
  314.     #db.begin_transaction(False)
  315.  
  316.     # Iterate all Debian packages
  317.  
  318.     # force apt to not write a pkgcache.bin
  319.     cache = apt.Cache(memonly=True)
  320.     count = len(cache)
  321.     for idx, pkg in enumerate(records):
  322.         # Print progress
  323.         if idx % 200 == 0: progress.progress(100*idx/count)
  324.  
  325.         document = xapian.Document()
  326.  
  327.         # The document data is the package name
  328.         document.set_data(pkg["Package"])
  329.  
  330.         # Index the package name with a special prefix, to be able to find this
  331.         # document by exact package name match
  332.         document.add_term("XP"+pkg["Package"])
  333.  
  334.         # Have all the various plugins index their things
  335.         for addon in addons:
  336.             addon.obj.indexDeb822(document, pkg)
  337.  
  338.         # Add the document to the index
  339.         db.add_document(document)
  340.     #db.commit_transaction();
  341.     db.flush()
  342.     progress.end()
  343.  
  344.  
  345. def writeValues(pathname, values, values_desc, progress):
  346.     """
  347.     Write the value information on the given file
  348.     """
  349.     progress.verbose("Writing value information to %s." % pathname)
  350.     out = open(pathname+".tmp", "w")
  351.  
  352.     print >>out, textwrap.dedent("""
  353.     # This file contains the mapping between names of numeric values indexed in the
  354.     # APT Xapian index and their index
  355.     #
  356.     # Xapian allows to index numeric values as well as keywords and to use them for
  357.     # all sorts of useful querying tricks.  However, every numeric value needs to
  358.     # have a unique index, and this configuration file is needed to record which
  359.     # indices are allocated and to provide a mnemonic name for them.
  360.     #
  361.     # The format is exactly like /etc/services with name, number and optional
  362.     # aliases, with the difference that the second column does not use the
  363.     # "/protocol" part, which would be meaningless here.
  364.     """).lstrip()
  365.  
  366.     for name, idx in sorted(values.iteritems(), key=lambda x: x[1]):
  367.         desc = values_desc[name]
  368.         print >>out, "%s\t%d\t# %s" % (name, idx, desc)
  369.  
  370.     out.close()
  371.     # Atomic update of the documentation
  372.     os.rename(pathname+".tmp", pathname)
  373.  
  374. def writeDoc(pathname, addons, progress):
  375.     """
  376.     Write the documentation in the given file
  377.     """
  378.     progress.verbose("Writing documentation to %s." % pathname)
  379.     # Collect the documentation
  380.     docinfo = []
  381.     for addon in addons:
  382.         try:
  383.             doc = addon.obj.doc()
  384.             if doc != None:
  385.                 docinfo.append(dict(
  386.                     name = doc['name'],
  387.                     shortDesc = doc['shortDesc'],
  388.                     fullDoc = doc['fullDoc']))
  389.         except:
  390.             # If a plugin has problem returning documentation, don't worry about it
  391.             progress.notice("Skipping documentation for plugin", addon.filename)
  392.  
  393.     # Write the documentation in pathname
  394.     out = open(pathname+".tmp", "w")
  395.     print >>out, textwrap.dedent("""
  396.     ===============
  397.     Database layout
  398.     ===============
  399.  
  400.     This Xapian database indexes Debian package information.  To query the
  401.     database, open it as ``%s/index``.
  402.  
  403.     Data are indexed either as terms or as values.  Words found in package
  404.     descriptions are indexed lowercase, and all other kinds of terms have an
  405.     uppercase prefix as documented below.
  406.  
  407.     Numbers are indexed as Xapian numeric values.  A list of the meaning of the
  408.     numeric values is found in ``%s``.
  409.  
  410.     The data sources used for indexing are:
  411.     """).lstrip() % (XAPIANDBPATH, XAPIANDBVALUES)
  412.  
  413.     for d in docinfo:
  414.         print >>out, " * %s: %s" % (d['name'], d['shortDesc'])
  415.  
  416.     print >>out, textwrap.dedent("""
  417.     This Xapian index follows the conventions for term prefixes described in
  418.     ``/usr/share/doc/xapian-omega/termprefixes.txt.gz``.
  419.  
  420.     Extra Debian data sources can define more extended prefixes (starting with
  421.     ``X``): their meaning is documented below together with the rest of the data
  422.     source documentation.
  423.  
  424.     At the very least, at least the package name (with the ``XP`` prefix) will
  425.     be present in every document in the database.  This allows to quickly
  426.     lookup a Xapian document by package name.
  427.  
  428.     The user data associated to a Xapian document is the package name.
  429.  
  430.  
  431.     -------------------
  432.     Active data sources
  433.     -------------------
  434.  
  435.     """)
  436.     for d in docinfo:
  437.         print >>out, d['name']
  438.         print >>out, '='*len(d['name'])
  439.         print >>out, textwrap.dedent(d['fullDoc'])
  440.         print >>out
  441.  
  442.     out.close()
  443.     # Atomic update of the documentation
  444.     os.rename(pathname+".tmp", pathname)
  445.  
  446.  
  447. #
  448. # Main program body
  449. #
  450.  
  451. from optparse import OptionParser
  452. import sys
  453.  
  454. VERSION="0.15"
  455.  
  456. class Parser(OptionParser):
  457.     def __init__(self, *args, **kwargs):
  458.         OptionParser.__init__(self, *args, **kwargs)
  459.  
  460.     def error(self, msg):
  461.         sys.stderr.write("%s: error: %s\n\n" % (self.get_prog_name(), msg))
  462.         self.print_help(sys.stderr)
  463.         sys.exit(2)
  464.  
  465. parser = Parser(usage="usage: %prog [options]",
  466.                 version="%prog "+ VERSION,
  467.                 description="Rebuild the Apt Xapian index")
  468. parser.add_option("-q", "--quiet", action="store_true", help="quiet mode: only output fatal errors")
  469. parser.add_option("-v", "--verbose", action="store_true", help="verbose mode")
  470. parser.add_option("-f", "--force", action="store_true", help="force database rebuild even if it's already up to date")
  471. parser.add_option("--pkgfile", action="store", help="do not use the APT cache, but the given Package file")
  472. parser.add_option("--batch-mode", action="store_true", help="Use progress reporting suitable from programatic parsing.")
  473.  
  474. (options, args) = parser.parse_args()
  475.  
  476.  
  477. # Here starts the main functionality.  Imports things here so we can do --help
  478. # without requiring lots of dependencies (this helps at least help2man at
  479. # package build time)
  480. import warnings
  481. # Yes, apt, thanks, I know, the api isn't stable, thank you so very much
  482. #warnings.simplefilter('ignore', FutureWarning)
  483. warnings.filterwarnings("ignore","apt API not stable yet")
  484. import apt
  485. warnings.resetwarnings()
  486. import os.path, re, imp, glob, xapian, textwrap, shutil, fcntl, errno, itertools, time
  487. import socket
  488. import cPickle as pickle
  489.  
  490. #if options.quiet: print "quiet"
  491. #if options.verbose: print "verbose"
  492. #if options.force: print "force"
  493.  
  494. # Instantiate the progress report
  495. if options.batch_mode:
  496.     progress = BatchProgress()
  497. elif options.quiet:
  498.     progress = SilentProgress()
  499. else:
  500.     progress = Progress()
  501.  
  502. if options.verbose:
  503.     progress.is_verbose = True
  504.  
  505. # Create the database directory if missing
  506. if not os.path.isdir(XAPIANDBPATH):
  507.     progress.verbose("Creating the database directory at %s" % XAPIANDBPATH)
  508.     os.mkdir(XAPIANDBPATH)
  509.  
  510. # Lock the session so that we prevent concurrent updates
  511. lockfd = os.open(XAPIANDBLOCK, os.O_RDWR | os.O_CREAT)
  512. lockpyfd = os.fdopen(lockfd)
  513. try:
  514.     fcntl.lockf(lockpyfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  515.     progress = ServerProgress(progress)
  516. except IOError, e:
  517.     if e.errno == errno.EACCES or e.errno == errno.EAGAIN:
  518.         progress.notice("Another update is already running: showing its progress.")
  519.         childProgress = ClientProgress(progress)
  520.         childProgress.loop()
  521.         sys.exit(0)
  522.     else:
  523.         raise
  524.  
  525. # Read values database
  526. #values = readValueDB(VALUESCONF, progress)
  527.  
  528. # Read the addons, in sorted order
  529. addons = readPlugins(PLUGINDIR, progress)
  530.  
  531. # Ensure that we have something to do
  532. if len(addons) == 0:
  533.     progress.notice("No indexing plugins found in %s" % PLUGINDIR)
  534.     sys.exit(1)
  535.  
  536. # Get the most recent modification timestamp of the data sources
  537. ds_timestamp = max([x.info['timestamp'] for x in addons])
  538.  
  539. # Get the timestamp of the last database update
  540. try:
  541.     cur_timestamp = os.path.getmtime(XAPIANDBSTAMP)
  542. except OSError, e:
  543.     cur_timestamp = 0
  544.     progress.notice("Reading current timestamp failed: %s. Assuming the index has not been created yet." % e)
  545.  
  546. if options.verbose:
  547.     progress.verbose("Most recent dataset:    %s." % time.ctime(ds_timestamp))
  548.     progress.verbose("Most recent update for: %s." % time.ctime(cur_timestamp))
  549.  
  550. # See if we need an update
  551. if ds_timestamp <= cur_timestamp:
  552.     if options.force:
  553.         progress.notice("The index %s is up to date, but rebuilding anyway as requested." % XAPIANDBPATH)
  554.     else:
  555.         progress.notice("The index %s is up to date" % XAPIANDBPATH)
  556.         sys.exit(0)
  557.  
  558. # Build the value database
  559. progress.verbose("Aggregating value information.")
  560. values = dict()
  561. values_seq = 1
  562. values_desc = dict()
  563. for addon in addons:
  564.     for v in addon.info.get("values", []):
  565.         values[v['name']] = values_seq
  566.         values_seq += 1
  567.         values_desc[v['name']] = v['desc']
  568.  
  569. # Tell the addons to do the long initialisation bits
  570. progress.verbose("Initializing plugins.")
  571. for addon in addons:
  572.     addon.obj.init(dict(values = values), progress)
  573.  
  574. # Create a new Xapian index with the content provided by the addons
  575. # Xapian takes care of preventing concurrent updates and removing the old
  576. # database if it's left over by a previous crashed update
  577.  
  578. # Create a temporary file name
  579. for idx in itertools.count(1):
  580.     tmpidxfname = "index.%d" % idx
  581.     dbdir = XAPIANDBPATH + "/" + tmpidxfname
  582.     if not os.path.exists(dbdir): break;
  583.  
  584. if options.pkgfile:
  585.     from debian_bundle import deb822
  586.     buildIndexDeb822(dbdir, deb822.Deb822.iter_paragraphs(open(options.pkgfile)), addons, progress)
  587. else:
  588.     buildIndex(dbdir, addons, progress)
  589.  
  590. # Update the 'index' symlink to point at the new index
  591. progress.verbose("Installing the new index.")
  592. try:
  593.     os.unlink(XAPIANDBPATH + "/index.tmp")
  594. except OSError:
  595.     # Ignore the error here: we're deleting it 'just in case', because symlink
  596.     # wouldn't delete it itself
  597.     pass
  598.  
  599. #os.symlink(tmpidxfname, XAPIANDBPATH + "/index.tmp")
  600. out = open(XAPIANDBPATH + "/index.tmp", "w")
  601. print >>out, "flint", os.path.join(os.path.abspath(XAPIANDBPATH), tmpidxfname)
  602. out.close()
  603. os.rename(XAPIANDBPATH + "/index.tmp", XAPIANDBPATH + "/index")
  604.  
  605. # Remove all other index.* directories that are not the newly created one
  606. for file in os.listdir(XAPIANDBPATH):
  607.     if not file.startswith("index."): continue
  608.     # Only delete directories
  609.     if not os.path.isdir(XAPIANDBPATH + "/" + file): continue
  610.     # Don't delete what we just created
  611.     if file == tmpidxfname: continue
  612.     fullpath = XAPIANDBPATH + "/" + file
  613.     progress.verbose("Removing old index %s." % fullpath)
  614.     shutil.rmtree(fullpath)
  615.  
  616. # Commit the changes and update the last update timestamp
  617. if not os.path.exists(XAPIANDBSTAMP):
  618.     open(XAPIANDBSTAMP, "w").close()
  619. os.utime(XAPIANDBSTAMP, (ds_timestamp, ds_timestamp))
  620.  
  621. writeValues(XAPIANDBVALUES, values, values_desc, progress)
  622. writeDoc(XAPIANDBDOC, addons, progress)
  623.  
  624. sys.exit(0)
  625.